package com.zzyl.nursing.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.domain.Room;
import com.zzyl.nursing.mapper.RoomMapper;
import com.zzyl.nursing.service.IRoomService;
import com.zzyl.nursing.vo.BedVo;
import com.zzyl.nursing.vo.DeviceInfo;
import com.zzyl.nursing.vo.RoomVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 房间Service业务层处理
 */
@Slf4j
@Service
public class RoomServiceImpl extends ServiceImpl<RoomMapper, Room> implements IRoomService {
    @Autowired
    private RoomMapper roomMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询房间
     *
     * @param id 房间主键
     * @return 房间
     */
    @Override
    public Room selectRoomById(Long id) {
        return getById(id);
    }

    /**
     * 查询房间列表
     *
     * @param room 房间
     * @return 房间
     */
    @Override
    public List<Room> selectRoomList(Room room) {
        return roomMapper.selectRoomList(room);
    }

    /**
     * 新增房间
     *
     * @param room 房间
     * @return 结果
     */
    @Override
    public int insertRoom(Room room) {
        return save(room) ? 1 : 0;
    }

    /**
     * 修改房间
     *
     * @param room 房间
     * @return 结果
     */
    @Override
    public int updateRoom(Room room) {
        return updateById(room) ? 1 : 0;
    }

    /**
     * 批量删除房间
     *
     * @param ids 需要删除的房间主键
     * @return 结果
     */
    @Override
    public int deleteRoomByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 根据楼层 id 获取房间视图对象列表
     *
     * @param floorId
     * @return
     */
    @Override
    public List<RoomVo> getRoomsByFloorId(Long floorId) {
        return roomMapper.selectByFloorId(floorId);
    }


    /**
     * 获取所有房间（负责老人）
     *
     * @param floorId
     * @return
     */
    @Override
    public List<RoomVo> getRoomsWithNurByFloorId(Long floorId) {
        return roomMapper.selectByFloorIdWithNur(floorId);
    }

    /*查询房间价钱*/
    @Override
    public RoomVo getRoomById(Long id) {
        RoomVo roomVo = roomMapper.selectRoomInfoById(id);
        return roomVo;
    }


    /**
     * 获取房间中的智能设备及数据
     *
     * @param floorId 楼层id
     */
    @Override
    public List<RoomVo> getRoomsWithDeviceByFloorId(Long floorId) {
        //1.查询楼层下的房间、房间里的设备、床、床上设备
        List<RoomVo> roomVos = roomMapper.selectRoomWithDeviceByFloorId(floorId);
        //1.1无内容直接返回空集合
        if (CollUtil.isEmpty(roomVos)) return Collections.emptyList();
        //2.遍历处理所有设备数据
        processDeviceData(roomVos);
        return roomVos;
    }

    /**
     * 处理房间和床位的设备数据
     *
     * @param roomVos 房间列表
     */
    private void processDeviceData(List<RoomVo> roomVos) {
        for (RoomVo roomVo : roomVos) {
            // 处理房间设备
            List<DeviceInfo> roomDevices = roomVo.getDeviceVos();
            if (CollUtil.isNotEmpty(roomDevices)) {
                updateDeviceData(roomDevices);
            }

            // 处理床位设备
            List<BedVo> bedVoList = roomVo.getBedVoList();
            if (CollUtil.isNotEmpty(bedVoList)) {
                for (BedVo bedVo : bedVoList) {
                    List<DeviceInfo> bedDevices = bedVo.getDeviceVos();
                    if (CollUtil.isNotEmpty(bedDevices)) {
                        updateDeviceData(bedDevices);
                    }
                }
            }
        }
    }

    /**
     * 更新设备数据
     *
     * @param devices 设备列表
     */
    private void updateDeviceData(List<DeviceInfo> devices) {
        for (DeviceInfo device : devices) {
            String deviceId = device.getIotId();
            try {
                String data = (String) redisTemplate.opsForHash().get(CacheConstants.IOT_DEVICE_LAST_DATA, deviceId);
                if (data != null) {
                    device.setDeviceDataVos(JSONUtil.toList(data, DeviceData.class));
                }
            } catch (Exception e) {
                log.error("获取设备数据失败，设备ID: {}", deviceId, e);
            }
        }
    }

}
